/**
 * 
 */
package com.objectdraw.server.commands;

import com.objectdraw.server.CommunicationServer;
import com.objectdraw.server.ObjectDrawServer;
import com.objectdraw.server.data.RequestData;
import com.objectdraw.server.data.ResponseData;

/**
 * Processes a control command from a client.
 * 
 * @author Harrison, jgulik, cfruehan
 * 
 */
public class ControlCommand extends Command {

	private final static String myCommand = "control";

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.objectdraw.server.commands.Command#processRequest(com.objectdraw.server.RequestData,
	 *      com.objectdraw.server.ResponseData)
	 */
	/**
	 * Takes a message with a control command and acts upon it.  If the param is "request" the client is 
	 * added to the control queue.  If the param is "release" the user releases control of the canvas and the
	 * next client in the queue gains control.  
	 */
	@Override
	public void processRequest(RequestData request, ResponseData response) {

		if (myCommand.equalsIgnoreCase(request.getCommand())) {
			System.out.println(myCommand + " Command");

			/**
			 * Expected Command:
			 * Client -> Control release|request <username> 
			 * Server -> Control canvas
			 * Server -> Control canvas ended
			 * Server -> Control canvas queued
			 */
			String opt[];
			if (request.getParams() != null) {
				opt = request.getParams().split(" ");
				if (opt.length >= 1) {
					ObjectDrawServer serv = ObjectDrawServer.getInstance();
					if ("request".equalsIgnoreCase(opt[0])) {
						serv.queueDrawer(opt[1]);
						response.addResponse("Control canvas queued");
						CommunicationServer.broadcast(response, serv.getDrawerConnection(opt[1]));
					} else if ("release".equalsIgnoreCase(opt[0])) {
							if(serv.getCurrentDrawer().equalsIgnoreCase(opt[1])){
								serv.releaseControl();
								serv.setCurrentDrawer(serv.getNextUserQueued());
						}
					}
				}
			}
		}
		// Pass the request on to the next person in line
		if (this.successor != null) {
			this.successor.processRequest(request, response);
		}
	}

}
